// 引入 axios
import axios from "axios";
import store from "@/store";
import JSONBIG from "json-bigint";
import router from "@/router";
// 封装 baseURL
const request = axios.create({
	baseURL: "http://120.25.227.191:8080",
	//baseURL: "http://localhost:8081/backend/api",
});

request.defaults.timeout = 7000;
request.defaults.transformResponse = [
	function (data) {
		const json = JSONBIG({
			storeAsString: true,
		});
		return json.parse(data);
	},
];
request.interceptors.request.use(
	(config) => {
		// 判断是否存在token，如果存在的话，则每个http header都加上token
		if (store.state.token) {
			config.headers["Authorization"] = store.state.token;
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);
request.interceptors.response.use(
	(response) => {
		if (response.data.code === 200) {
			return response;
		} else if (response.data.code === 602) {
			store.commit("logout");
			router.push("/");
			return response;
		} else if (response.data.code === 403) {
			router.back();
			return response;
		} else if (response.data.code === 601) {
			router.push("/login");
			return response;
		} else {
			return response;
		}
	},
	(error) => {
		return Promise.reject(error);
	}
);

export default request;
// 向外暴露 request
